package com.itheima.service;


import com.itheima.dao.StudentDao;
import com.itheima.domian.Student;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class StudentService {
    private static final Logger LOGGER = LoggerFactory.getLogger(StudentService.class);

    //获取集合中最大的id
    private int getMaxId() {
        StudentDao studentDao = new StudentDao();
        //获取到dao里反序列化出的集合
        ArrayList<Student> studentArrayList = studentDao.readFromFile();
        //给studentArrayList集合排序
        Collections.sort(studentArrayList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int a = o1.getId() - o2.getId();
                return a;
            }
        });
        //根据最大索引获取id
        Integer id = studentArrayList.get(studentArrayList.size() - 1).getId();
        LOGGER.info("[服务器端]最大id为:" + id);
        return id;
    }
    //获得最小索引
    private int getMinId() {
        ArrayList<Student> studentArrayList = new StudentDao().readFromFile();
        Collections.sort(studentArrayList, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int a = o1.getId() - o2.getId();
                return a;
            }
        });
        Integer minId = studentArrayList.get(0).getId();
        LOGGER.info("[服务器端]最小id为:" + minId);
        return minId;
    }

    public void deleteStudent(String s,BufferedWriter bw,Socket accept) {
        Integer deleteId = Integer.parseInt(s);
        //判断id是否在范围
        if (deleteId >getMaxId()||deleteId<getMinId()) {
            try {
                bw.write("删除失败!!!id不存在");
                bw.flush();
                accept.shutdownOutput();
                accept.close();
            } catch (IOException e) {
                LOGGER.warn("[服务器]删除失败!");
            }
        }else {
            new StudentDao().deleteStudent(deleteId);
            try {
                bw.write("删除成功!");
                bw.flush();
                accept.shutdownOutput();
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void findAllStudent(Socket accept,BufferedWriter bw) throws IOException {
        ArrayList<Student> students = new StudentDao().readFromFile();
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int a = o1.getId() - o2.getId();
                return a;
            }
        });
        for (Student student : students) {
            System.out.println(student.toString());
            try {
                bw.write("id:" + student.getId() + "name:" + student.getName() + "性别:"
                        + student.getSex() + "年龄:" + student.getAge());
                bw.newLine();
                bw.flush();

            } catch (IOException e) {
                LOGGER.warn("[服务器端]向客户端发送数据错误!");
            }
        }
        accept.shutdownOutput();
    }

    public void updateStudent(String str,BufferedWriter bw,Socket accept) {
        String s = str.substring(3);
        String[] split = s.split(",");
        //将字符转成int
        Integer id = Integer.parseInt(split[0]);
        //判断是否在范围
        if (id>getMaxId()||id < getMinId()){
            try {
                bw.write("修改失败");
                bw.flush();
                bw.close();
                accept.close();
            } catch (IOException e) {
                LOGGER.warn("[服务器]修改失败!");
            }
        }else {
            ArrayList<Student> students = new StudentDao().readFromFile();
            //判断集合中是否有指定id
            int flag = -1;
            for (int i = 0; i < students.size(); i++) {
                if (id.equals(students.get(i).getId())) {
                    flag = i;
                }
            }
            //flag不为-1则代表有
            if (flag != -1) {
                Student student = new Student(getMaxId() + 1, split[1], split[2], Integer.parseInt(split[3]));
                new StudentDao().updateStudent(flag,student);
                try {
                    bw.write("修改完成!");
                    bw.flush();
                    bw.close();
                    accept.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            //flag为-1则代表没有,所以失败
            }else {
                try {
                    bw.write("修改失败");
                    bw.flush();
                    bw.close();
                    accept.close();
                } catch (IOException e) {
                    LOGGER.warn("[服务器]修改失败!");
                }
            }
        }

    }

    //没用的方法
    public void findStudent(char[] chars, BufferedWriter bw) {
        String str = new String(chars);
        String s = str.substring(3);
        int id = Integer.parseInt(s);
        try {
            if (id > getMaxId()) {
                bw.write("查询的id非法!");

            } else {
                Student student = new StudentDao().findStudent(id);
                bw.write("id:" + student.getId() + "name:" + student.getName() + "性别:" + student.getSex() + "年龄:" + student.getAge());
                bw.flush();
                bw.close();
            }
        } catch (IOException e) {
            LOGGER.warn("[客户端]用户查询的id非法!");
        }
    }

    @Test
    public void addStudent(String str, BufferedWriter bw) throws IOException {
        String s = str.substring(3);
        String[] split = s.split(",");
        if (Integer.parseInt(split[2]) <= 120 && Integer.parseInt(split[2]) >= 0) {
            Student student = new Student(getMaxId() + 1, split[0], split[1], Integer.parseInt(split[2]));
            new StudentDao().addStudent(student);
            bw.write("添加成功!");
            bw.flush();
            bw.close();
        } else {
            bw.write("添加失败!!!");
            bw.flush();
            bw.close();
        }
    }
}
